package net.wantongtech.xa.uploadbasicinfo.service;

import cn.com.taiji.sdk.tools.JsonTools;
import com.google.common.collect.Lists;
import com.wtkj.constant.NewClearingConstant;
import com.wtkj.constant.ObuSignEnum;
import com.wtkj.vo.RandomGUID;
import com.wtkj.vo.dzzf.base.clearing.TransOutExtend;
import com.wtkj.vo.dzzf.base.jygl.TransOut;
import com.wtkj.vo.dzzf.base.jygl.TransOutDspt;
import com.wtkj.vo.dzzf.base.qxsjz.entity.DisputeTransOut;
import com.wtkj.vo.dzzf.base.qxsjz.entity.PortalTransOut;
import com.wtkj.vo.dzzf.base.qxsjz.entity.SwipeSplitOut;
import com.wtkj.vo.dzzf.base.xxdl.InteractionOrgMsgReceive;
import com.wtkj.zwxt.clearing.vo.clear.item.EtcClearItem;
import com.wtkj.zwxt.clearing.vo.clear.model.EtcClearModel;
import com.wtkj.zwxt.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.FillHistoryDisputedDataDao;
import net.wantongtech.xa.uploadbasicinfo.util.ClearingCommonUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.csource.client.FastDFSClient;
import org.csource.common.MyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 填充历史争议交易数据服务实现
 *
 * @author MaShibo
 * 日期 :  2020/2/10
 */
@Slf4j
@Service
public class FillHistoryDisputedDataService {

    @Resource
    private FillHistoryDisputedDataDao fillHistoryDisputedDataDao;

    private final TransactionTemplate transactionTemplate;

    public FillHistoryDisputedDataService(PlatformTransactionManager transactionManager) {
        this.transactionTemplate = new TransactionTemplate(transactionManager);
    }

    public void fill() {
        List<String> receiveIdList = Lists.newArrayList(
                "1ACB7548-118E-8889-7217-2D7C58763E1D"
        );
        receiveIdList.forEach(receiveId -> {
            try {
                processSingle(receiveId);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        });
    }

    private void processSingle(String receiveId) throws MyException, IOException {
        InteractionOrgMsgReceive ormObj = new InteractionOrgMsgReceive();
        ormObj.setListID(receiveId);
        InteractionOrgMsgReceive receiveMsg = (InteractionOrgMsgReceive) fillHistoryDisputedDataDao.queryObject(ormObj);
        if (receiveMsg == null) {
            log.warn("ListId为：{}的接收表数据不存在", receiveId);
            return;
        }
        String storePath = receiveMsg.getStorePath();
        log.info("ListId：{}，对应文件存储路径：{}", receiveId, storePath);

        Integer storeFlag = receiveMsg.getStoreFlag();

        String json;
        if (storeFlag == 1) {
            json = FastDFSClient.downLoadFile(storePath, null);
        } else {
            json = FileUtils.readFileToString(new File(storePath), "UTF-8");
        }

        EtcClearModel model = JsonTools.json2Object(json, EtcClearModel.class);
        model.getClearDetail().forEach(clearDetail -> {
            List<EtcClearItem> clearItemList = clearDetail.getClearItems();
            clearItemList.forEach(clearItem -> {
                Integer fileType = clearItem.getFileType();
                if (fileType == NewClearingConstant.FileType.DISPUTE.getValue()) {
                    Long fileId = clearItem.getFileId();
                    boolean existsNew = fillHistoryDisputedDataDao.existsNewDisputedId(fileId);
                    boolean existsOld = fillHistoryDisputedDataDao.existsOldFileId(fileId);
                    log.info("fileId：{}，存在新：{}，存在老：{}", fileId, existsNew ? "是" : "否", existsOld ? "是" : "否");
                    if (!existsNew && existsOld) {
                        try {
                            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                                @Override
                                protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                                    processFileId(fileId);
                                }
                            });
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            });

        });
    }


    private void processFileId(Long fileId) {
        List<TransOutDspt> transOutDsptList = fillHistoryDisputedDataDao.queryOldDsptTransOutInfo(fileId);
        if (transOutDsptList.isEmpty()) {
            log.info("fileId：{}，不存在对应的老系统争议数据", fileId);
            return;
        }
        log.info("共查询出{}条，fileId为{}对应的老系统争议数据", transOutDsptList.size(), fileId);


        for (TransOutDspt transOutDspt : transOutDsptList) {
            Map<String, Object> extendProperties = transOutDspt.getExtendProperties();
            Object transactionIdObj = extendProperties.get("TRANSACTIONID");
            if (transactionIdObj == null) {
                log.info("fileId：{}，查询获取transactionId失败", fileId);
                return;
            }
            TransOut ormObj = new TransOut();
            String consumeId = transOutDspt.getConsumeID();
            ormObj.setConsumeID(consumeId);
            TransOut transOut = (TransOut) fillHistoryDisputedDataDao.queryObject(ormObj);
            if (transOut == null) {
                log.info("fileId：{}，consumeId：{}，对应原始交易记录不存在", fileId, consumeId);
                throw new BusinessException("原始交易记录不存在");
            }

            TransOutExtend transOutExtend = fillHistoryDisputedDataDao.queryTransOutExtendByConsumeId(consumeId);
            if (transOutExtend == null) {
                log.info("consumeId：{}对应扩展交易数据不存在", consumeId);
                throw new BusinessException("扩展交易数据不存在");
            }

            String transactionId = transactionIdObj.toString();
            DisputeTransOut disputeTransOut = new DisputeTransOut();
            disputeTransOut.setTransactionId(transactionId);
            Long messageId = transOut.getMsgID();
            disputeTransOut.setMessageId(messageId);
            disputeTransOut.setTransType(NewClearingConstant.TransType.CARD_TRANS.getValue());
            String serviceId = transOutDspt.getServiceID();
            if (StringUtils.isNotBlank(serviceId)) {
                disputeTransOut.setTollProvinceId(ClearingCommonUtils.convert2NewTransferNo(serviceId));
            }
            String issuerId = transOutDspt.getIssuerID();
            if (StringUtils.isNotBlank(issuerId)) {
                disputeTransOut.setIssuerId(ClearingCommonUtils.convert2NewTransferNo(issuerId));
            }
            disputeTransOut.setOptOn(transOutDspt.getOptOn());
            disputeTransOut.setDisputeType(transOutDspt.getDsptType());
            disputeTransOut.setDisputedId(fileId);
            disputeTransOut.setOthDisputes(transOutDspt.getOthDspTps());
            disputeTransOut.setResult(transOutDspt.getDsptStatus());
            disputeTransOut.setDealOn(transOutDspt.getDealOn());
            disputeTransOut.setDealBy(transOutDspt.getDealBy());
            disputeTransOut.setReason(transOutDspt.getReason());
            disputeTransOut.setSendFlag(transOutDspt.getSendFlag());
            disputeTransOut.setIsRefund(transOutDspt.getIsRefund());
            disputeTransOut.setCreateTime(transOutDspt.getCreateOn());
            disputeTransOut.setDealFlag(transOutDspt.getDealFlag());
            disputeTransOut.setPendFileId(transOutDspt.getPendFileID());
            Long pendMsgID = transOutDspt.getPendMsgID();
            if (pendMsgID != null) {
                disputeTransOut.setPendMessageId(pendMsgID);
            }
            fillHistoryDisputedDataDao.createValueObject(disputeTransOut);


            PortalTransOut portalTransOut = new PortalTransOut();
            portalTransOut.setTransactionId(transactionId);
            String etcCardId = transOut.getNetNo() + transOut.getCardId();
            log.info("卡号为：{}", etcCardId);
            portalTransOut.setEtcCardId(etcCardId);
            String originalIssuerId = transOut.getOriginalIssuerId();
            portalTransOut.setIssuerId(ClearingCommonUtils.convert2NewTransferNo(originalIssuerId));
            String originalServiceId = transOut.getOriginalServiceId();
            portalTransOut.setTollProvinceId(ClearingCommonUtils.convert2NewTransferNo(originalServiceId));
            portalTransOut.setMessageId(messageId);
            portalTransOut.setAccountId(transOut.getAccountID());
            portalTransOut.setEtcCardType(transOut.getCardType());
            portalTransOut.setServiceType(transOut.getServiceTypeForMsg());
            portalTransOut.setFee(ClearingCommonUtils.unitConvert(transOut.getFee()));
            portalTransOut.setDescription(transOut.getDescription());
            portalTransOut.setCreateTime(transOut.getReceiveOn());
            portalTransOut.setBalanceOn(transOut.getBalanceOn());
            portalTransOut.setState(transOut.getState());
            portalTransOut.setClearFlag(transOut.getClearFlag());
            Integer laneID = transOut.getLaneID();
            portalTransOut.setExTollLaneId(laneID.toString());
            portalTransOut.setVehiclePlate(transOut.getVehplateByCard());
            portalTransOut.setVehicleColor(transOut.getVehcolor());
            portalTransOut.setPrivilegeType(transOut.getPrivilegeType());
            portalTransOut.setFundAccountName(transOut.getFundAccountName());
            portalTransOut.setType(NewClearingConstant.TransType.CARD_TRANS.getValue());
            portalTransOut.setObuSign(ObuSignEnum.DOUBLE_TYPE.getValue());
            portalTransOut.setObuId(transOut.getOBUContractNO());
            portalTransOut.setTransTime(transOut.getTime());
            portalTransOut.setChannelType(transOutExtend.getChannelType());
            portalTransOut.setSignSource(transOutExtend.getSignSource());
            portalTransOut.setIsIntegrated(3);
            portalTransOut.setIntegratedId("旧系统交易");
            portalTransOut.setEnTollStationName(transOutExtend.getEnTollStationName());
            portalTransOut.setExTollStationName(transOutExtend.getExTollStationName());
            fillHistoryDisputedDataDao.createValueObject(portalTransOut);

            SwipeSplitOut swipeSplitOut = new SwipeSplitOut();
            swipeSplitOut.setDefineId(new RandomGUID().toString());
            swipeSplitOut.setTransactionId(transactionId);
            swipeSplitOut.setTollProvinceId(portalTransOut.getTollProvinceId());
            swipeSplitOut.setTollFee(portalTransOut.getFee());
            swipeSplitOut.setCreateTime(portalTransOut.getCreateTime());
            fillHistoryDisputedDataDao.createValueObject(swipeSplitOut);

        }


    }
}
